/*
 * =====================================================================================
 *
 *       Filename:  
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  06/04/14 10:01:41
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Andy (gk), andy_y_li@163.com
 *        Company:  RD
 *
 * =====================================================================================
 */


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include "utility.h"

#define	READ	0
#define	WRITE	1 

void opps(char *s1,char *s2)
{
    fprintf(stderr,"%s",s1);
    perror(s2);
    exit(1);
}

void TurnToupper(char * str)
{
    while(*str)
    {
        *str = _toupper(*str);
        str++;
    }

}

void TurnTolower(char * str)
{
    while(*str)
    {
        *str = _tolower(*str);
        str++;
    }
}


void ClearBuffer()
{
    while(getchar() !='\n');
}

void Debug(const char *str, ...)
{

}


FILE *diy_popen(const char *cmd,const char *mode)
{
//	FILE *fp;
	int pipe_end[2],pid;
	int parent_end,child_end;

	if (*mode == 'r') {
		parent_end = READ;
		child_end = WRITE; 
	}
	else if (*mode == 'w') {
		parent_end = WRITE;
		child_end = READ;
	}else return NULL;

	// get a pipe
	if (pipe(pipe_end) == -1){
		return NULL;	
	}
	// get a process
	if ((pid = fork()) == -1) {
		close(pipe_end[0]);
		close(pipe_end[1]);
		return NULL;
	}
	// parent code
	if (pid > 0) {
		close(pipe_end[child_end]);
		//dup2(pipe_end[parent_end],parent_end);
		//close(pipe_end[parent_end]);
		return fdopen(pipe_end[parent_end],mode);	
	}
	// childe code
	if (pid == 0) {
		close(pipe_end[parent_end]);
		dup2(pipe_end[child_end],child_end);
		close(pipe_end[child_end]);
		execlp("/bin/sh",cmd,"-",NULL);
		exit(1);
		
	}
	else
		return NULL;
}


